package com.bk.bookviews.common;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.bk.bookviews.enums.MsgEnum;
import com.bk.bookviews.exception.BusinessExceptionEnum;
import com.bk.bookviews.exception.SystemExceptionHandler;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass=true,exposeProxy=true)

/**
 * @description aop分页拦截
 */
public class PageInfoAop {

    private Logger logger = LoggerFactory.getLogger(SystemExceptionHandler.class);

    /**
     * @description 分页时拦截方法，并自动分页包装信息
     * @param proceedingJoinPoint
     * @return
     */
    @Around("execution(public com.bk.bookviews.common.Pagination com.bk.bookviews.service.impl.*.*(..))")
    public Pagination around(ProceedingJoinPoint proceedingJoinPoint) {
        logger.info("分页拦截器开始");
        //执行方法操作
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //请求的页数
        String pageNum = request.getHeader("pageNum");
        //请求的条数
        String pageSize = request.getHeader("pageSize");

        if(StringUtils.isBlank(pageNum)||StringUtils.isBlank(pageSize)){
            Pagination pagination = new Pagination();
            pagination.setCode(BusinessExceptionEnum.PAGE_ARGS_IS_NULL.getCode());
            pagination.setErrMsg(BusinessExceptionEnum.PAGE_ARGS_IS_NULL.getErrMsg());
            return pagination;
        }

        //方法执行前分页
        PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
        try {
            Pagination pagination = (Pagination)proceedingJoinPoint.proceed();
            //获取得到的数据
            Page<?> page = (Page<?>)pagination.getData();
            //设置分页信息
            pagination.setPageInfo(pagination.new PageInfo(page.getTotal(),page.getPageNum(),page.getPageSize()));
            pagination.setCode(MsgEnum.SUCCESS.getCode());
            return pagination;
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
